package com.wutianyi.utils;

import java.util.HashMap;
import java.util.Map;

import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;

/**
 * @author hanjiewu 通用工具类
 */
public class Utils {
	
	private static final int DEFAULT_PAGE_SIZE = 20;
	private static ObjectMapper objectMapper = new ObjectMapper();
	private static final Map<String, String> parameters;
	
	static {
		parameters = new HashMap<String, String>();
		parameters.put("charset", "UTF-8");
	}
	
	/**
	 * @param total
	 * @param pageNo
	 * @param pageSize
	 * @return
	 */
	public static int getPosition(int total, int pageNo, int pageSize) {
		if (pageNo <= 0) {
			pageNo = 1;
		}
		if (pageSize <= 0) {
			pageSize = DEFAULT_PAGE_SIZE;
		}
		int totalNo = total % pageSize == 0 ? total / pageSize : total / pageSize + 1;
		if (pageNo > totalNo) {
			pageNo = totalNo;
		}
		return (pageNo - 1) * pageSize;
	}
	
	public static ResponseEntity<String> createJsonResponse(int result, String msg, Object info) {
		String response = createJsonResult(result, msg, info);
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(new MediaType(MediaType.APPLICATION_JSON, parameters));
		
		return new ResponseEntity<String>(response, headers, HttpStatus.OK);
	}
	
	public static String createJsonResult(int result, String msg, Object info) {
		Map<String, Object> results = new HashMap<String, Object>();
		results.put("r", result);
		results.put("msg", msg);
		if(null != info) {
			results.put("info", info);
		}
		try {
			return objectMapper.writeValueAsString(results);
		} catch (Exception e) {

		}
		return "";
	}
}
